package com.zcmob.web.admanagement.db;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.zcmob.web.admanagement.util.IncomeType;
import com.zcmob.web.admanagement.vo.ActiveType;
import com.zcmob.web.admanagement.vo.AdUser;
import com.zcmob.web.admanagement.vo.AdvInfo;
import com.zcmob.web.admanagement.vo.AppBid;
import com.zcmob.web.admanagement.vo.AppInfo;
import com.zcmob.web.admanagement.vo.ServiceType;

public class AppDao {

    private SqlMapClient smc = null;
    private static AppDao appDao = new AppDao();
    Logger logger = LoggerFactory.getLogger("dmzlog");
    
    private AppDao() {
        init();
    }

    private void init() {
        if (smc == null) {
            Reader rd;
            try {
                rd = Resources.getResourceAsReader("SqlMapConfig.xml");
                smc = SqlMapClientBuilder.buildSqlMapClient(rd);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static AppDao getInstance() {

        return appDao;

    }

    public AdUser getAdUserByUsername (String username) {
        
        AdUser result = null;
        
        try {
            result = (AdUser)smc.queryForObject("total.getUserByUsername", username);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return result;
    }
    
    public boolean isAppExit(String packagename) {
        
        AppInfo app = null;
        boolean flg = false;
        try {
            app = (AppInfo)smc.queryForObject("total.getAppByPackagename", packagename);
            if (app != null) {
                flg = true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return flg;
    }
    
    public AppInfo getAppByPackagename(String packagename){
        AppInfo app = null;
        try {
            app = (AppInfo)smc.queryForObject("total.getAppByPackagename", packagename);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return app;
    }
    
    public void insertApp(AppInfo app){
        try {
            Integer id = (Integer)smc.insert("total.AddApp", app);
            
            app.setId(id);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public boolean updateStatus(AppInfo app){
        boolean flg = false;
        
        try {
            int i = smc.update("total.UpdateStatus", app);
            if (i == 1) {
                flg = true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        } 
        return flg;
    }
    
    public void insertAdv(AdvInfo adv){
        try {
            Integer id = (Integer)smc.insert("total.AddAdv", adv);
            
            adv.setId(id);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public List<ServiceType> getServiceList(){
        List<ServiceType> result = null;
        try {
            result = (List<ServiceType>)smc.queryForList("total.getServiceByid", -1);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    
    public ServiceType getServiceTypeByid(int id){
        ServiceType result = null;
        try {
            result = (ServiceType)smc.queryForObject("total.getServiceByid", id);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    
    public void insertAppBid(AppBid appbid){
        try {
            
            smc.insert("total.AddAppBid", appbid);
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
    }
    
    public void insertAd_user(AdUser aduser) {
        
        try {
            smc.insert("total.AddAdUser", aduser);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public List<AppInfo> getAppsByUserId(int userid) {
        List<AppInfo> list = null;
        List<AppBid> middleList = null;
        try {
            list = (List<AppInfo>) smc.queryForList("total.listAppByUserid", userid);
            middleList = (List<AppBid>) smc.queryForList("total.getAppBidByUserid", userid);
            Map<Integer, Map<Integer, Double>> tmpMap = new HashMap<Integer, Map<Integer, Double>>(middleList.size());
            for (AppBid bid : middleList) {
                if (tmpMap.get(bid.getAppid()) == null) {
                    tmpMap.put(bid.getAppid(), new HashMap<Integer, Double>());
                }

                // 特殊处理，当serviceid大于4时，用的别的体验套餐，取巧直接用2作为key供下面for循环logtimeuserfee赋值 
                tmpMap.get(bid.getAppid()).put(bid.getServiceid() > 4 ? 2 : bid.getServiceid(), bid.getAd_unit_bid());
                // 注意：这里跟api不同，返回的是广告主的单价，api中这段逻辑是返回的用户所看到的单价

            }

            for (AppInfo app : list) {
                //TODO: 
                app.setDownloadFee(tmpMap.get(app.getId()).get(IncomeType.DOWLOAD) == null ? 0 : tmpMap
                        .get(app.getId()).get(IncomeType.DOWLOAD));
                app.setLongtimeuserFee(tmpMap.get(app.getId()).get(IncomeType.LONG_TIME_USER) == null ? 0 : tmpMap.get(
                        app.getId()).get(IncomeType.LONG_TIME_USER));
                app.setRateFee(tmpMap.get(app.getId()).get(IncomeType.RATE) == null ? 0 : tmpMap.get(app.getId()).get(
                        IncomeType.RATE));
                app.setForwardFee(tmpMap.get(app.getId()).get(IncomeType.FORWARD_WEIBO) == null ? 0 : tmpMap.get(
                        app.getId()).get(IncomeType.FORWARD_WEIBO));
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }
        return list;
    }
    
    public List<AdvInfo> getAdv() {
        List<AdvInfo> list = null;
        try {
            list = (List<AdvInfo>) smc.queryForList("total.listAdv");
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }
        return list;
    }
    
    public List<ActiveType> getActiveType(){
        List<ActiveType> list = null;
        try {
            list = (List<ActiveType>) smc.queryForList("total.listActiveType");
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("", e);
        }
        return list;
    }
    
    public static void main(String[] args) {
        List<AppInfo> list = AppDao.getInstance().getAppsByUserId(0);
        System.out.println(list.get(0));
    }
    
    
    
}
